String
Strings are a fundamental type in any programming language, including Groovy, where they are used extensively for storing and manipulating textual data. This tutorial will help non-programmers understand how to work with strings in Groovy, covering basic concepts, operations, and common methods.
What is a String?
A string in programming is essentially a sequence of characters. In Groovy, like many other languages, strings are enclosed in quotes. You can use either single quotes ('
) or double quotes ("
), but double quotes allow for string interpolation (inserting variable values directly into the string).
Creating Strings
Here’s how you can create a string in Groovy:
def singleQuoteString = 'Hello, world!'
def doubleQuoteString = "Hello, world!"
String Interpolation
One of the powerful features of Groovy is string interpolation, which is the ability to embed expressions within string literals directly. You use ${expression}
or just $variableName
inside double-quoted strings:
def name = "Alice"
def greeting = "Hello, $name!"
println(greeting) // Outputs: Hello, Alice!
Common String Methods
Groovy strings have methods that perform various operations, such as changing case, finding substrings, or replacing parts of the string. Here are a few useful methods:
-
Length of a string: Returns the number of characters in the string.
def message = "Hello, world!" println(message.length()) // Outputs: 13
-
Convert to upper case:
println(message.toUpperCase()) // Outputs: HELLO, WORLD!
-
Convert to lower case:
println(message.toLowerCase()) // Outputs: hello, world!
-
Replace parts of the string:
println(message.replace("Hello", "Goodbye")) // Outputs: Goodbye, world!
-
Substring: Extracting parts of the string.
println(message.substring(7)) // Outputs: world!
Concatenation
You can combine strings using the +
operator or the string interpolation feature:
def firstName = "John"
def lastName = "Doe"
def fullName = firstName + " " + lastName
println(fullName) // Outputs: John Doe
Multiline Strings
Groovy also supports multiline strings, which are great for including formatted text without needing to insert newline characters manually:
def lyrics = """Line 1
Line 2
Line 3"""
println(lyrics)
Useful Groovy String Functions
-
Trim: Removes whitespace from both ends of a string.
def extraSpace = " Hello, world! " println(extraSpace.trim()) // Outputs: Hello, world!
-
Starts with and Ends with: Checks if the string starts or ends with a substring.
println("Groovy".startsWith("Gro")) // Outputs: true println("Groovy".endsWith("vy")) // Outputs: true
-
Contains: Checks if the string contains a certain sequence of characters.
println("Groovy".contains("oo")) // Outputs: true
Exercises
Exercise 1: Reverse a String
Task: Write a Groovy script that reverses a string. For example, if the input is "hello"
, the output should be "olleh"
.
Exercise 2: Palindrome Checker
Task: Create a function in Groovy that checks whether a string is a palindrome (reads the same backward as forward). For example, "radar"
should return true, while "hello"
should return false.
Exercise 3: Count Vowels
Task: Write a script that counts the number of vowels in a given string. For instance, in the string "hello world"
, the output should be 3
.
Exercise 4: Concatenate and Capitalize
Task: Given two strings, concatenate them and then convert the entire resulting string to uppercase. For example, "hello"
and "world"
should become "HELLO WORLD"
.
Exercise 5: Find and Replace
Task: Create a function that takes a string and replaces all occurrences of the word "Java"
with "Groovy"
. For instance, transforming the string "I love Java"
should result in "I love Groovy"
.
Solutions
Solution to Exercise 1: Reverse a String
def reverseString(String str) {
return str.reverse()
}
println(reverseString("hello")) // Outputs: olleh
Solution to Exercise 2: Palindrome Checker
def isPalindrome(String str) {
return str == str.reverse()
}
println(isPalindrome("radar")) // Outputs: true
println(isPalindrome("hello")) // Outputs: false
Solution to Exercise 3: Count Vowels
def countVowels(String str) {
def vowels = ['a', 'e', 'i', 'o', 'u']
int count = 0
str.toLowerCase().each { char ->
if (char in vowels) {
count++
}
}
return count
}
println(countVowels("hello world")) // Outputs: 3
Solution to Exercise 4: Concatenate and Capitalize
def concatenateAndCapitalize(String str1, String str2) {
return (str1 + " " + str2).toUpperCase()
}
println(concatenateAndCapitalize("hello", "world")) // Outputs: HELLO WORLD
Solution to Exercise 5: Find and Replace
def replaceJavaWithGroovy(String str) {
return str.replaceAll("Java", "Groovy")
}
println(replaceJavaWithGroovy("I love Java")) // Outputs: I love Groovy